//package com.zijing2333.adaptivescheduling;
//
//
//
//import static com.zijing2333.adaptivescheduling.SwitcherManager.utils.NetworkUtil.getIP;
//
//import androidx.appcompat.app.AppCompatActivity;
//import androidx.appcompat.widget.AppCompatEditText;
//
//import android.os.Bundle;
//import android.util.Log;
//import android.view.View;
//import android.widget.Button;
//import android.widget.LinearLayout;
//import android.widget.RadioGroup;
//import android.widget.TextView;
//import android.widget.Toast;
//
//import com.google.android.material.textfield.TextInputEditText;
//
//import com.zijing2333.adaptivescheduling.SwitcherManager.Switcher;
//import com.zijing2333.adaptivescheduling.SwitcherManager.client.ClientCallback;
//import com.zijing2333.adaptivescheduling.SwitcherManager.server.ServerCallback;
//import com.zijing2333.adaptivescheduling.SwitcherManager.utils.ThreadUtil;
//import com.zijing2333.servicerunner.TaskInfo;
//
//import java.util.Collections;
//import java.util.HashMap;
//import java.util.Map;
//
//public class MainActivity2 extends AppCompatActivity implements ServerCallback, ClientCallback {
//
//    private static final String TAG = "fun_MainActivity";
//    private StringBuffer buffer = new StringBuffer();
//    //当前是否为服务端
//    private boolean isServer = true;
//
//    //Socket服务是否打开
//    private boolean openSocket = false;
//
//    //Socket服务是否连接
//    private boolean connectSocket = false;
//
////    private SocketServer mSocketServer ;
//
////    private SocketClient mSocketClient ;
//
//
//
//    // Instance of the SwitcherManager for managing execution states
//    private Switcher mSwitcher;
//
//    private String ServerServiceID = "001";
//    private String ClientServiceID = "001";
//
//    private static MainActivity2 instance;
//
//    public static MainActivity2 getInstance(){
//        return instance;
//    }
//    //倒计时任务，所有功能都能实现
//
//
//
//    private Map<String, TaskInfo> Js_Service_map;
//
//
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main2);
//
//        instance = this;//初始化instance
//
//        mSwitcher = new Switcher(this);
////        mSchedulerManager = new SchedulerManager(this);
////        Js_Service_map = Collections.synchronizedMap(new HashMap<>());
//        //这里放入的是倒计时服务，其中taskParams表示的是任务的执行状态，目前还没有弄好
////        TaskInfo taskInfo1 = new TaskInfo("001",jsCode1,true,"Waiting");
////        TaskInfo taskInfo2 = new TaskInfo("002",jsCode2,true,"waiting");
////        TaskInfo taskInfo3 = new TaskInfo("003",jsCode3,true,"waiting");
////        Js_Service_map.put(taskInfo1.getTaskId(),taskInfo1);
////        Js_Service_map.put(taskInfo2.getTaskId(),taskInfo2);
////        Js_Service_map.put(taskInfo3.getTaskId(),taskInfo3);
//
//        initView();
//    }
//
//    private void initView() {
//        //对应  界面中的“Ip地址”
//        TextView tv_ip_address = (TextView) findViewById(R.id.tv_ip_address);
//        tv_ip_address.setText("IP地址:"+getIP(this));
//        RadioGroup radioGroup = (RadioGroup)findViewById(R.id.rg);
//        RadioGroup radioGroup2 = (RadioGroup)findViewById(R.id.rg2); //服务端的JS列表
//        RadioGroup radioGroup3 = (RadioGroup)findViewById(R.id.rg3); //客户端的JS列表
//        LinearLayout lay_server = findViewById(R.id.lay_server);
//        LinearLayout lay_client = findViewById(R.id.lay_client);
////        AppCompatEditText appCompatEditText = findViewById(R.id.et_msg);
//
//        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                if (checkedId == R.id.rb_server) {
//                    isServer = true;
//                } else if (checkedId == R.id.rb_client){
//                    isServer = false;
//                }
//                lay_server.setVisibility(isServer? View.VISIBLE:View.GONE);
//                lay_client.setVisibility(isServer?View.GONE:View.VISIBLE);
////                appCompatEditText.setHint(isServer? "发送给客户端":"发送给服务端");
//            }
//        });
//        radioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                if (checkedId == R.id.rb_Server_Js_Service1){
//                    ServerServiceID = "001";
//                }else if (checkedId == R.id.rb_Server_Js_Service2){
//                    ServerServiceID = "002";
//                }else if (checkedId == R.id.rb_Server_Js_Service3){
//                    ServerServiceID = "003";
//                }
//            }
//        });
//
//        radioGroup3.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                if (checkedId == R.id.rb_Client_Js_Service1){
//                    ClientServiceID = "001";
//                }else if (checkedId == R.id.rb_Client_Js_Service2){
//                    ClientServiceID = "002";
//                }else if (checkedId == R.id.rb_Client_Js_Service3){
//                    ClientServiceID = "003";
//                }
//            }
//        });
//
//        //开启服务/关闭服务 服务端处理
//        findViewById(R.id.btn_start_service).setOnClickListener(this::startService);
//        //连接服务/断开连接 客户端处理
//        findViewById(R.id.btn_connect_service).setOnClickListener(this::connectService);
//        //发送消息 给 服务端/客户端
////        findViewById(R.id.btn_send_msg).setOnClickListener(this::sendMessage);
//
//        //开启客户端JS服务
//        findViewById(R.id.btn_start_client_JS).setOnClickListener(this::startClientJs);
//
//        //关闭客户端JS服务
//        findViewById(R.id.btn_stop_client_JS).setOnClickListener(this::stopClientJs);
//        //关闭服务端JS服务
//        findViewById(R.id.btn_stop_server_JS).setOnClickListener(this::stopServerJs);
//        //开启服务端JS服务的通知
//        findViewById(R.id.btn_start_migration).setOnClickListener(this::startClientMigration);
//        //恢复服务端数据
//        findViewById(R.id.btn_data_migration).setOnClickListener(this::sendDataMigration);
//        //展示客户端JS服务的状态
//        findViewById(R.id.btn_show_client_JS_state).setOnClickListener(this::showClinetJsState);
//        //展示服务端JS服务的状态
//        findViewById(R.id.btn_show_server_JS_state).setOnClickListener(this::showServerJsState);
//
//    }
//
//    //收到部署器发来的通知后，切换器会先存储一下任务，然后通知JS管理模块启动JS任务
//    public void onNotificationReceived(TaskInfo taskInfo,int state){
////        ChannelManager.getInstance().addJsMap(taskInfo); //存储一下服务-----在SwitcherInteractionWithDeployer类中存了
//        Log.d(TAG, "onNotificationReceived: ------MainActivity2-----0");
//        boolean isSuccess = mSwitcher.dispatchJsTask(taskInfo.getTaskId(),taskInfo);
//        Log.d(TAG, "onNotificationReceived: ------MainActivity2-----1");
//
//        if (!isSuccess){
//            Log.d(TAG, "切换器部署服务成功");
//        }
//    }
//
//    //展示服务端JS任务的当前倒计时状态
//    private void showServerJsState(View view) {
//        Toast.makeText(getApplication(),"JS任务当前状态"+mSwitcher.getCurrentExecutionState(ServerServiceID),Toast.LENGTH_SHORT).show();
//    }
//
//    //展示客户端JS任务的当前倒计时状态
//    private void showClinetJsState(View view) {
//        Toast.makeText(getApplication(),"JS任务当前状态"+mSwitcher.getCurrentExecutionState(ClientServiceID),Toast.LENGTH_SHORT).show();
//    }
//
//
//
//    //A设备给B设备发送部署服务的通知
//    private void startClientMigration(View view) {
//        //让用户输入需要迁移的Js服务名称
////        TextInputEditText et_migration_JS_Name = findViewById(R.id.et_migration_JS_Name);
////        String ServiceName = et_migration_JS_Name.getText().toString();
//        String data = ""; //这里data 为空，表示的是发送通知，让B设备部署Js服务
//        sendMessageToServer(ClientServiceID,data);//这里调用Socket通信，这里是发送部署服务的通知
//        Log.d(TAG, "B端部署服务通知发送成功----------------- ");
//
//    }
//    //A设备给B设备发送流转数据
//    private void sendDataMigration(View view) {
////        TextInputEditText et_migration_JS_Name = findViewById(R.id.et_migration_JS_Name);
////        String ServiceName = et_migration_JS_Name.getText().toString();
////        boolean requiresUI = Js_Service_map.get(ClientServiceID).isHasUI();
////        String data = mSwitcherManager.getCurrentExecutionState(ClientServiceID,requiresUI);
//        String data = mSwitcher.getCurrentExecutionState(ClientServiceID);
//        Toast.makeText(getApplication(),"Service1 save data:"+data ,Toast.LENGTH_SHORT).show();
//        sendMessageToServer(ClientServiceID, data);//这里调用Socket通信，将data发送过去
//        Log.d(TAG, "流转数据发送成功----------------- ");
//    }
//
//    private void stopServerJs(View view) {
////        TextInputEditText et_migration_JS_Name_Server = findViewById(R.id.et_migration_JS_Name_Server);
////        String ServiceName = et_migration_JS_Name_Server.getText().toString();
////        boolean requiresUI = Js_Service_map.get(ServerServiceID).isHasUI();
////        mSwitcherManager.stopJSExecution(ServerServiceID,requiresUI);
//        mSwitcher.stopJSExecution(ServerServiceID);
//        Toast.makeText(getApplication(),"Service2 Stop:" ,Toast.LENGTH_SHORT).show();
//    }
//
//    private void stopClientJs(View view) {
////        TextInputEditText et_migration_JS_Name = findViewById(R.id.et_migration_JS_Name);
////        String ServiceName = et_migration_JS_Name.getText().toString();
////        boolean requiresUI = Js_Service_map.get(ClientServiceID).isHasUI();
////        mSwitcherManager.stopJSExecution(ClientServiceID,requiresUI);
//        mSwitcher.stopJSExecution(ClientServiceID);
//        Toast.makeText(getApplication(),"Service1 Stop:" ,Toast.LENGTH_SHORT).show();
//    }
//
//
//    //启动客户端的JS服务
//    private void startClientJs(View view) {
////        TextInputEditText et_migration_JS_Name = findViewById(R.id.et_migration_JS_Name);
////        String ServiceName = et_migration_JS_Name.getText().toString();
//        Log.d(TAG, "ClientServiceId:==============="+ClientServiceID);
//        String code = Js_Service_map.get(ClientServiceID).getTaskCode();
//        Log.d(TAG, "code:=============="+code);
////        boolean requiresUI = Js_Service_map.get(ClientServiceID).isHasUI();
////        Log.d(TAG, "requiresUI: "+requiresUI);
////        mSchedulerManager.sendJSResource(ClientServiceID, code,requiresUI);
//        boolean isSuccess = mSwitcher.dispatchJsTask(ClientServiceID,Js_Service_map.get(ClientServiceID));
//        Toast.makeText(getApplication(),"Service Start:" ,Toast.LENGTH_SHORT).show();
//        Log.d(TAG, "设备A上的JS服务已开启---------------- ");
//    }
//
//
//    private void restoreServerJsData(String ServiceId){
////        boolean requiresUI = Js_Service_map.get(ServerServiceID).isHasUI();
////        mSwitcherManager.restoreServiceDataState(ServiceName,data,requiresUI); //这里需要将“01”替换为ServiceName
////        mSwitcher.restoreServiceDataState(ServiceId);
//
//        Log.d(TAG, "设备B上已完成状态恢复 ");
//    }
//
//    /**
//     * 开启服务端的服务
//     * @param view
//     */
//    private void startService(View view) {
//        if (openSocket){
////            mSocketServer.stopServer();
//            ChannelManager.getInstance().stopServer();//思考是closeChannel还是stopServer
//            openSocket=false;
//        }else {
////            mSocketServer = new SocketServer();
////            mSocketServer.startServer(this);
//            ChannelManager.getInstance().startServer(this);
//            openSocket = true;
//        }
//        showInfo(openSocket?"开启Socket服务":"关闭Socket服务");
//        Button btn_start_service = findViewById(R.id.btn_start_service);
//        btn_start_service.setText(openSocket?"关闭Socket服务":"开启Socket服务");
//
//    }
//
//    //在UI线程上进行显示
//    private void showInfo(String info) {
//        buffer.append(info).append("\n");
//        TextView tv_info = findViewById(R.id.tv_info);
////        runOnUiThread(new Runnable() {
////            @Override
////            public void run() {
////                tv_info.setText(buffer.toString());
////            }
////        });
//
//        ThreadUtil.RunInMainThread(new ThreadUtil.ThreadPram()
//        {
//            @Override
//            public void Function()
//            {
//                tv_info.setText(buffer.toString());
//            }
//        });
//    }
//
//
//    /**
//     * 连接服务
//     * @param view
//     */
//    private void connectService(View view) {
//        TextInputEditText et_ip_address = findViewById(R.id.et_ip_address);
//        String ip = et_ip_address.getText().toString();
//        if (ip.isEmpty()){
//            showMsg("请输入Ip地址");
//            return;
//        }
//        if (connectSocket){
////            mSocketClient.closeConnect();
//            ChannelManager.getInstance().stopClient2(ClientServiceID);
//            connectSocket = false;
//        }else {
////            mSocketClient = new SocketClient();
////            mSocketClient.connectServer(ip,this);
//            ChannelManager.getInstance().startClient2(ip, this,ClientServiceID);
//            connectSocket = true;
//        }
//        showInfo(connectSocket?"连接Socket服务":"关闭Socket连接");
//        Button btn_connect_service = findViewById(R.id.btn_connect_service);
//        btn_connect_service.setText(connectSocket?"关闭Socket连接":"连接Socket服务");
//
//    }
//
//    private void showMsg(String msg) {
//        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
//    }
//
//
//
//    /**
//     * 发送消息，先判断是服务端还是客户端，然后再调用端的发送信息的方法
//     * @param view
//     */
//    private void sendMessage(View view) {
////        AppCompatEditText et_msg = findViewById(R.id.et_msg);
//        String msg = "";
//        if (msg.isEmpty()){
//            showMsg("请输入要发送的消息");
//            return;
//        }
//        //标志能否发送
//        boolean isSend = false;
//
//        if (openSocket){
//            isSend=openSocket;
//        }else if (connectSocket){
//            isSend = connectSocket;
//        }else{
//            isSend = false;
//        }
//
//
//        if (!isSend){
//            showMsg("当前未开启服务或连接服务");
//            return;
//        }
//        if (isServer){
////            mSocketServer.sendToClient(msg);
////            ChannelManager.getInstance().sendMesToClient(msg);
//        }else {
////            mSocketClient.sendToServer(msg);
////            ChannelManager.getInstance().senMesToServer(msg);
//        }
////        et_msg.setText("");
//
//    }
//    private void sendMessageToServer(String ServiceId, String data) {
//        String msg = data;
////        if (msg.isEmpty()){
////            showMsg("请输入要发送的消息");
////            return;
////        }
//        Log.d(TAG, "正在发送通知或数据给设备B--------------");
//        ChannelManager.getInstance().senMesToServer(ServiceId,msg);
//    }
//
//
//    //部署服务端的JS服务
//    private void deployJs(String ServiceName) {
//        TaskInfo taskInfo = Js_Service_map.get(ServiceName);
////        mSchedulerManager.sendJSResource(ServiceName,code,requiresUI);
//        boolean isSuccess = mSwitcher.dispatchJsTask(taskInfo.getTaskId(),taskInfo);
//        //这里需要将“01”替换为ServiceName--------------
//        Log.d(TAG, "设备B上已开启服务 ");
//    }
//
//
//    @Override
//    public void receiveServerMsg(String msg) {
//        showInfo("Server："+msg);
//    }
//
//    @Override
//    public void receiveClientMsg(boolean success, String ServiceId,String msg) {
//        if (msg.isEmpty()){ //这里是部署服务
//            showInfo("本机部署服务成功");
//            Log.d(TAG, "receiveClientMsg: =========ServiceName:"+ServiceId);
//            ThreadUtil.RunInMainThread(new ThreadUtil.ThreadPram() {
//                @Override
//                public void Function() {
//                    deployJs(ServiceId);
//                }
//            });
//        }else { //这里是恢复服务数据
//            showInfo("Client:"+msg);
//            ThreadUtil.RunInMainThread(new ThreadUtil.ThreadPram() {
//                @Override
//                public void Function() {
//                    restoreServerJsData(ServiceId);
//                }
//            });
//        }
//    }
//
//
//
//    @Override
//    public void otherMsg(String msg) {
//        showInfo(msg);
//    }
//}